import logging
import os
import sys
from typing import Union, Callable

import uvicorn
from fastapi import FastAPI, HTTPException

from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.exceptions import ExceptionMiddleware


from api.utils import general_exception_handler, app

from api.routers import sample, models, standradlibs

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    level=logging.INFO,  # 设置日志级别
    handlers=[logging.StreamHandler()]  # 将日志输出到控制台
)

logger = logging.getLogger(__name__)

app.add_middleware(ExceptionMiddleware, handlers={Exception: general_exception_handler})

app.add_middleware(  # 解决跨域问题
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(sample.router, prefix="/sample", tags=["样本"])

app.include_router(models.router, prefix="/model", tags=["模型"])

app.include_router(standradlibs.router, prefix="/standrad", tags=["标准库"])

if __name__ == "__main__":
    main_path = ""

    base_name = os.path.basename(sys.executable)
    if base_name == "python.exe":
        main_path = os.path.dirname(__file__)
    else:
        main_path = os.path.dirname(sys.executable)
    os.environ['MAIN_FILE_PATH'] = main_path
    uvicorn.run(app, host="localhost", port=8001)
